package com.yb.framework.core.utils;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

public class SecurityUtil {
	
	/**
	 * 获取用户
	 **/
	public static User getLoginUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if(authentication != null && !"anonymousUser".equals(authentication.getPrincipal())) {
			return (User) authentication.getPrincipal();
		}
		return null;
	}
	
	/**
	 * 获取用户名
	 **/
	public static String getUsername() {
		if(getLoginUser() != null) {
			return getLoginUser().getUsername();
		}
		return null;
	}
	
	/**
	 * 获取用户权限
	 **/
	public static List<String> getAuthorities() {
		List<String> authorities = new ArrayList<String>();
		if(getLoginUser() != null) {
			for (GrantedAuthority grantedAuthority : getLoginUser().getAuthorities()) {
				if(StringUtil.isNotEmpty(grantedAuthority.getAuthority())) {
					authorities.add(grantedAuthority.getAuthority());
				}
			}
		}
		return authorities;
	}
	
	// 是否为超级管理员
	public static boolean isAdmin() {
		if("root".equals(getUsername()) || "admin".equals(getUsername())) {
			return true;
		}
		return false;
	}
}
